import React, { useState, useEffect, useRef } from 'react';
import Sidebar from './sidebar/Sidebar';
import EditPanel from './editPanel/EditPanel';
import NotesAPI from './api';
import { exportNotesToCSV, importNotesFromCSV } from './utils/importExport';

const App: React.FC = () => {
  const [notes, setNotes] = useState<Note[]>([]);
  const [activeNote, setActiveNote] = useState<Note | null>(null);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [noteToDelete, setNoteToDelete] = useState<number | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    refreshNotes();
  }, []);

  const refreshNotes = () => {
    const notes = NotesAPI.getAllNotes();
    setNotes(notes);
    if (notes.length > 0) {
      setActiveNote(notes[0]);
    }
  };

  const handleNoteSelect = (noteId: number) => {
    const selectedNote = notes.find((note) => note.id === noteId);
    setActiveNote(selectedNote || null);
  };

  const handleNoteAdd = () => {
    const newNote = {
      id: 0,
      title: "新笔记",
      body: "",
      updated: new Date().toISOString(),
      tags: []
    };
    NotesAPI.saveNote(newNote);
    refreshNotes();
  };

  const handleNoteEdit = (title: string, body: string) => {
    if (activeNote) {
      NotesAPI.saveNote({
        ...activeNote,
        title,
        body,
      });
      refreshNotes();
    }
  };

  const handleNoteDelete = (noteId: number) => {
    setNoteToDelete(noteId);
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (noteToDelete !== null) {
      NotesAPI.deleteNote(noteToDelete);
      refreshNotes();
      setShowDeleteDialog(false);
      setNoteToDelete(null);
    }
  };

  const cancelDelete = () => {
    setShowDeleteDialog(false);
    setNoteToDelete(null);
  };

  const handleExport = () => {
    const csv = exportNotesToCSV(notes);
    const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
    const a = document.createElement('a');
    a.href = url;
    a.download = `notes_${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleImport = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    
    try {
      const text = await file.text();
      const importedNotes = importNotesFromCSV(text);
      importedNotes.forEach(note => NotesAPI.saveNote(note));
      refreshNotes();
    } catch (error) {
      console.error('导入失败:', error);
    }
  };

  return (
    <div className="notes">
      <Sidebar
        notes={notes}
        onNoteSelect={handleNoteSelect}
        onNoteAdd={handleNoteAdd}
        onNoteDelete={handleNoteDelete}
        activeNote={activeNote}
        onImport={() => fileInputRef.current?.click()}
        onExport={handleExport}
      />
      <EditPanel note={activeNote} onNoteEdit={handleNoteEdit} />
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleImport}
        accept=".csv"
        style={{ display: 'none' }}
      />
      {showDeleteDialog && (
        <div className="delete-dialog">
          <h3>删除笔记？</h3>
          <p>该操作不可撤销</p>
          <button onClick={confirmDelete}>确认删除</button>
          <button onClick={cancelDelete}>取消</button>
        </div>
      )}
    </div>
  );
};

export default App;
